<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="合同编号" prop="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 280px"
        />
      </el-form-item>
           <el-form-item label="老人姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
          style="width: 280px"
        />
      </el-form-item>
           <el-form-item label="合同状态" prop="contractStatus">
        <el-select v-model="queryParams.contractStatus" placeholder="请选择合同状态" clearable style="width: 280px">
          <el-option label="未生效" value="0" />
          <el-option label="生效中" value="1" />
          <el-option label="已过期" value="2" />
          <el-option label="已失效" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="合同期限" style="width: 360px">
        <el-date-picker
          v-model="daterangeStartDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
 
      <el-form-item>
        <el-button icon="Refresh" @click="resetQuery" style="margin-left: 10px;">重置</el-button>
        <el-button type="primary" icon="Search" @click="handleQuery" style="margin-left: 30px;">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:contract:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:contract:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:contract:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:contract:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="70" />
      <el-table-column label="合同编号" align="center" prop="contractNo" width="100px"/>
      <el-table-column label="合同名称" align="center" prop="contractName" width="100px"/>
       <el-table-column label="老人姓名" align="center" prop="elderly.name" width="100px" />
      <el-table-column label="老人身份证号" align="center" prop="elderly.idCard" width="180px" />
      <el-table-column label="合同期限开始时间" align="center" prop="startDate" width="130px">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同期限结束时间" align="center" prop="endDate" width="130px">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" prop="contractStatus">
        <template #default="scope">
          <el-tag 
            :type="getStatusTagType(scope.row.contractStatus)"
            :style="getStatusStyle(scope.row.contractStatus)"
            effect="light"
          >
            {{ getStatusText(scope.row.contractStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="sysUser.nickName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:contract:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:contract:remove']">删除</el-button>
           <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同跟踪对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="contractRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入合同名称" />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNo">
          <el-input v-model="form.contractNo" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item label="老人外键编号" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人外键编号" />
        </el-form-item>
        <el-form-item label="合同期限开始时间" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择合同期限开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同期限结束时间" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择合同期限结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同状态" prop="contractStatus">
          <el-select v-model="form.contractStatus" placeholder="请选择合同状态">
            <el-option label="未生效" value="0" />
            <el-option label="生效中" value="1" />
            <el-option label="已过期" value="2" />
            <el-option label="已失效" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="签约时间" prop="signTime">
          <el-date-picker clearable
            v-model="form.signTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择签约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同文件" prop="contractFile">
          <file-upload v-model="form.contractFile"/>
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="丙方姓名" prop="partyCName">
          <el-input v-model="form.partyCName" placeholder="请输入丙方姓名" />
        </el-form-item>
        <el-form-item label="丙方联系电话" prop="partyCPhone">
          <el-input v-model="form.partyCPhone" placeholder="请输入丙方联系电话" />
        </el-form-item>
        <el-form-item label="解除提交人" prop="terminationSubmitter">
          <el-input v-model="form.terminationSubmitter" placeholder="请输入解除提交人" />
        </el-form-item>
        <el-form-item label="解除时间" prop="terminationTime">
          <el-date-picker clearable
            v-model="form.terminationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择解除时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="解除协议文件" prop="terminationAgreement">
          <el-input v-model="form.terminationAgreement" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="入住管理表外键编号" prop="checkInManagementId">
          <el-input v-model="form.checkInManagementId" placeholder="请输入入住管理表外键编号" />
        </el-form-item>
        <el-form-item label="额外字段1" prop="extraField1">
          <el-input v-model="form.extraField1" placeholder="请输入额外字段1" />
        </el-form-item>
        <el-form-item label="额外字段2" prop="extraField2">
          <el-input v-model="form.extraField2" placeholder="请输入额外字段2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Contract">
import { listContract, getContract, delContract, addContract, updateContract } from "@/api/system/contract"
import { getCurrentInstance, ref, reactive, toRefs } from "vue"
import { useRouter } from "vue-router"

const router = useRouter()

const { proxy } = getCurrentInstance()

const contractList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeStartDate = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractNo: null,
    elderlyId: null,
    startDate: null,
    endDate: null,
    contractStatus: null,
    name: null,
    idCard: null,
  },
  rules: {
    contractName: [
      { required: true, message: "合同名称不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询合同跟踪列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (daterangeStartDate.value && daterangeStartDate.value.length > 0) {
    queryParams.value.params["beginStartDate"] = daterangeStartDate.value[0]
    queryParams.value.params["endStartDate"] = daterangeStartDate.value[1]
  }
  listContract(queryParams.value).then(response => {
    contractList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
// 在列表页的handleDetail方法中添加预加载
async function handleDetail(row) {
  try {
    loading.value = true
    
    // 直接使用当前行数据作为预加载数据，避免再次请求API
    console.log("传递给详情页的数据:", row);
    
    // 确保传递完整的数据结构
    const dataToPass = {
      ...row,
      // 确保嵌套对象存在
      elderly: row.elderly || {},
      sysUser: row.sysUser || {}
    };
    
    router.push({
      path: '/system/contract/xq',
      query: { 
        id: row.id,
        // 携带预加载数据
        preload: JSON.stringify(dataToPass)
      }
    })
  } catch (e) {
    console.error("导航到详情页失败:", e);
    proxy.$modal.msgError("加载详情失败")
  } finally {
    loading.value = false
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    contractName: null,
    contractNo: null,
    elderlyId: null,
    startDate: null,
    endDate: null,
    contractStatus: null,
    signTime: null,
    contractFile: null,
    creator: null,
    createTime: null,
    partyCName: null,
    partyCPhone: null,
    terminationSubmitter: null,
    terminationTime: null,
    terminationAgreement: null,
    checkInManagementId: null,
    extraField1: null,
    extraField2: null

  }
  proxy.resetForm("contractRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeStartDate.value = []
  queryParams.value.contractNo = null
  queryParams.value.name = null
  queryParams.value.contractStatus = null
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加合同跟踪"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getContract(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改合同跟踪"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["contractRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateContract(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addContract(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除合同跟踪编号为"' + _ids + '"的数据项？').then(function() {
    return delContract(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/contract/export', {
    ...queryParams.value
  }, `contract_${new Date().getTime()}.xlsx`)
}

/** 获取合同状态文本 */
function getStatusText(status) {
  const statusMap = {
    '0': '未生效',
    '1': '生效中', 
    '2': '已过期',
    '3': '已失效'
  }
  return statusMap[status] || status
}

/** 获取合同状态标签类型 */
function getStatusTagType(status) {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'warning', 
    3: 'danger',
    '0': 'info',
    '1': 'success',
    '2': 'warning', 
    '3': 'danger',
    '未生效': 'info',
    '生效中': 'success',
    '已过期': 'warning',
    '已失效': 'danger'
  }
  return typeMap[status] || 'info'
}

/** 获取合同状态样式 */
function getStatusStyle(status) {
  const styleMap = {
    0: 'background-color: #909399; color: white; border-color: #909399;',
    1: 'background-color: #67C23A; color: white; border-color: #67C23A;',
    2: 'background-color: #E6A23C; color: white; border-color: #E6A23C;',
    3: 'background-color: #F56C6C; color: white; border-color: #F56C6C;',
    '0': 'background-color: #909399; color: white; border-color: #909399;',
    '1': 'background-color: #67C23A; color: white; border-color: #67C23A;',
    '2': 'background-color: #E6A23C; color: white; border-color: #E6A23C;',
    '3': 'background-color: #F56C6C; color: white; border-color: #F56C6C;',
    '未生效': 'background-color: #909399; color: white; border-color: #909399;',
    '生效中': 'background-color: #67C23A; color: white; border-color: #67C23A;',
    '已过期': 'background-color: #E6A23C; color: white; border-color: #E6A23C;',
    '已失效': 'background-color: #F56C6C; color: white; border-color: #F56C6C;'
  }
  return styleMap[status] || 'background-color: #909399; color: white; border-color: #909399;'
}

getList()
</script>
